package com.netease.research.service.impl;

import com.netease.research.Vo.CartVo;
import com.netease.research.common.ServerResponse;
import com.netease.research.dao.CartMapper;
import com.netease.research.dao.ProductMapper;
import com.netease.research.pojo.Cart;
import com.netease.research.pojo.Product;
import com.netease.research.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("iCartService")
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public ServerResponse<Cart> add(Integer userId, Integer productId, Integer quantity) {
        Cart cart = cartMapper.selectByProductIdUserId(productId, userId);
        if (cart == null) {
//            购物车没有该商品
            cart = new Cart();
            cart.setUserId(userId);
            cart.setProductId(productId);
            cart.setQuantity(quantity);
            cartMapper.insert(cart);
        } else {
//            购物车已经有该商品，增加数量即可
            quantity += cart.getQuantity();
            cart.setQuantity(quantity);
            cartMapper.updateQuantityByPrimaryKey(cart.getId(), quantity);
        }
        return ServerResponse.createBySuccess(cart);
    }

    @Override
    public ServerResponse<List<CartVo>> list(Integer userId) {
        List<Cart> cartList = cartMapper.selectByUserId(userId);
        List<CartVo> cartVoList = new ArrayList<>();
        for (Cart item : cartList) {
            CartVo vo = assembleCartVo(item);
            if(vo != null) {
                cartVoList.add(vo);
            }
        }
        return ServerResponse.createBySuccess(cartVoList);
    }

    private CartVo assembleCartVo(Cart cart) {
        CartVo vo = new CartVo();
        vo.setId(cart.getId());
        vo.setQuantity(cart.getQuantity());
        int productId = cart.getProductId();
        Product product = productMapper.selectByPrimaryKey(productId);
//        情况：seller删除了buyer已经加入购物车的商品，则product==null
        if (product != null) {
            vo.setPrice(product.getPrice());
            vo.setTitle(product.getTitle());
            return vo;
        }else{
            return null;
        }
    }

    @Override
    public void clear(Integer userId) {
        cartMapper.deleteByUserId(userId);
    }
}
